//
//  QainliUserLoginVC.swift
//  todoios
//
//  Created by qianli on 2025/5/22.
//

import Foundation
import SwiftyUserDefaults

class QainliUserLoginVC: QianliParentNaviVC {
    private var F8MC1HIDRYWx1xED:UIButton?
    private var cWTPhgOUvVenvUrY: InputMailView?
    private var viVV4GQEwb5QJDfC: InputPasswordView?
    private var rG0bPuFNG6wJFOou: GradientBtn?
    private var wcMRaK5LBXrZ0wJz:UIImageView?
    private var IsODuVFzV1ZBF8I1:String?
    
    var loginOKBlock: os_block_t?
    var autoLoginOKBlock: os_block_t?
    
    override func GHL4Rhb91XYBer27() {
        self.zdMpsGrNncVEHdYA(title: LocalizedString("LOGIN"))
        let logoView = UIImageView(frame: CGRect(x: qianli_pm_width/2 - 80/2, y: topSpace+15, width: 80, height: 80))
        view.addSubview(logoView)
        logoView.image = "qianli_logo_main".qianli_R_image
        
        var iTop = topSpace+30+80+50
        
        self.cWTPhgOUvVenvUrY = InputMailView(frame:CGRect(x: 35, y: iTop, width: qianli_pm_width-70, height: 60) , icoName: "qianli_field_email", placeholder: LocalizedString("Please enter a email"), showclear: true)
        if let inputmail = self.cWTPhgOUvVenvUrY{
            view.addSubview(inputmail)
            inputmail.backgroundColor = .systemBackground
            inputmail.layer.cornerRadius = 30
            inputmail.DdITqvtW560pCIVj(type: .emailAddress)
        }
        
        iTop+=60+20
        self.viVV4GQEwb5QJDfC = InputPasswordView(frame:CGRect(x: 35, y: iTop, width: qianli_pm_width-70, height: 60))
        if let inputpw = self.viVV4GQEwb5QJDfC{
            view.addSubview(inputpw)
            inputpw.backgroundColor = .systemBackground
            inputpw.layer.cornerRadius = 30
        }
        
        iTop+=60+20
        self.F8MC1HIDRYWx1xED = UIButton(type: .custom)
        if let radioBtn = self.F8MC1HIDRYWx1xED{
            radioBtn.setImage("qianli_checkbox_n".qianli_R_image, for: .normal)
            radioBtn.setImage("qianli_checkbox_h".qianli_R_image, for: .selected)
            radioBtn.frame = CGRect(x: 50, y: iTop+5, width: 20, height: 20)
            radioBtn.isSelected = false
            radioBtn.contentMode = .center
            view.addSubview(radioBtn)
            radioBtn.touch_With_Block { [weak self] sender in
                QianliVibrateEnum.light.vibrate()
                sender.isSelected = !sender.isSelected
                self?.view.endEditing(true)
            }
        }
        
        let textView = UITextView(frame: CGRect(x: 50+20+5, y: iTop, width: qianli_pm_width-35-24-10, height: 30))
        textView.isEditable = false
        textView.isSelectable = true //为true才能触发点击链接
        textView.delegate = self
        textView.font = .systemFont(ofSize: 13)
        textView.backgroundColor = .clear
        view.addSubview(textView)
        
        let msg = LocalizedString("SERVICE AGREEMENT & PRIVACY POLICY")
        let paragraphStyle = NSMutableParagraphStyle()
//        paragraphStyle.lineSpacing = 10 // 设置行距
        let myMutableString = NSMutableAttributedString(
                    string: msg,
                    attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 13),
                                 NSAttributedString.Key.paragraphStyle:paragraphStyle,
                                 NSAttributedString.Key.foregroundColor:UIColor.label])
        let range_1:NSRange = (msg as NSString).range(of:LocalizedString("SERVICE AGREEMENT"))
        myMutableString.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.systemBlue,
                                       NSAttributedString.Key.link:URL(string: "action://userProtocol") as Any], range: range_1)
        
        let range_2:NSRange = (msg as NSString).range(of:LocalizedString("PRIVACY POLICY"))
        myMutableString.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.systemBlue,
                                       NSAttributedString.Key.link:URL(string: "action://userPrivate") as Any], range: range_2)
        textView.attributedText = myMutableString
        
        iTop+=20+50
        self.rG0bPuFNG6wJFOou = GradientBtn(frame: CGRect(x: 40, y: iTop, width: qianli_pm_width-80, height: 48), title: LocalizedString("Login Now"))
        if let loginbutton = self.rG0bPuFNG6wJFOou{
            view.addSubview(loginbutton)
            loginbutton.touch_With_Block { [weak self] sender in
                if let self = self{
                    self.UWRdl1krZEkBno2y()
                }
            }
        }
        
        iTop+=48+30
        let registBtn = UIButton(frame: CGRect(x: qianli_pm_width/2-15-120, y: iTop, width: 120, height: 20))
        view.addSubview(registBtn)
        registBtn.setTitle(LocalizedString("Mail Login"), for: .normal)
        registBtn.setTitleColor(.secondaryLabel, for: .normal)
        registBtn.titleLabel?.font = .systemFont(ofSize: 14)
        registBtn.touch_With_Block { [weak self]sender in
            if let self = self{
                self.ph2lqG56246k5nHN()
            }
        }
        
        let forgetBtn = UIButton(frame: CGRect(x: qianli_pm_width/2+15, y: iTop, width: 120, height: 20))
        view.addSubview(forgetBtn)
        forgetBtn.setTitle(LocalizedString("FORGET PW"), for: .normal)
        forgetBtn.setTitleColor(.secondaryLabel, for: .normal)
        forgetBtn.titleLabel?.font = .systemFont(ofSize: 14)
        forgetBtn.touch_With_Block { [weak self]sender in
            if let self = self{
                self.I78xJTIx1AbmwUKi()
            }
        }
        
        iTop+=20+50
        let kefuBtn = UIButton(frame: CGRect(x: qianli_pm_width/2-60, y: iTop, width: 120, height: 20))
        view.addSubview(kefuBtn)
        kefuBtn.setTitle(LocalizedString("LINK US"), for: .normal)
        kefuBtn.setTitleColor(UIColor(hexString: "#3964ff"), for: .normal)
        kefuBtn.titleLabel?.font = .systemFont(ofSize: 13)
        kefuBtn.touch_With_Block { sender in
            let customUrl = Defaults[\.customerURL]
            QianliUniversalFunc.PqHXCLMrbGaK2xN1(customUrl) { success in
            }
        }
    }
    
    override func aB7kFqI8MB6DRPQC() {
        if let msg = self.IsODuVFzV1ZBF8I1{
            self.view.Qianli_Toast(msg,delayTime: 3.0)
        }
    }
    
    public func drLNPcLilSQNLR0o(_ msg:String){
        self.IsODuVFzV1ZBF8I1 = msg
    }
}

extension QainliUserLoginVC{
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true) //关闭键盘
    }
    
    func UWRdl1krZEkBno2y(){
        self.view.endEditing(true)
        
        guard let btnLogin = self.rG0bPuFNG6wJFOou else{ //self.codeButton?.isEnabled = true
            return
        }
        
        guard let inputmail = self.cWTPhgOUvVenvUrY,let inputpw = self.viVV4GQEwb5QJDfC else{
            return
        }
        let s_mail = inputmail.JRrMFFk8vXgbNlUN()
        if s_mail.isEmpty || !isValidEmail(s_mail){
            self.view.Qianli_Toast(LocalizedString("Please enter a valid email"))
            QianliVibrateEnum.oldSchool.vibrate()
            return
        }
        let s_pw = inputpw.JRrMFFk8vXgbNlUN()
        if s_pw.isEmpty || s_pw.count<4{
            self.view.Qianli_Toast(LocalizedString("Please enter a valid password"))
            QianliVibrateEnum.oldSchool.vibrate()
            return
        }
        
        if let btnSelect = self.F8MC1HIDRYWx1xED{
            if !btnSelect.isSelected{
                view.Qianli_Toast(LocalizedString("Please read and agree to our Terms of Service & Privacy Policy."))
                QianliVibrateEnum.oldSchool.vibrate()
                return
            }
        }
   
        QianliVibrateEnum.light.vibrate()
        if let lgimg = self.wcMRaK5LBXrZ0wJz{
            lgimg.removeFromSuperview()
        }
        btnLogin.setTitle(LocalizedString("Logining..."), for: .normal)
        
        self.wcMRaK5LBXrZ0wJz = UIImageView(frame: CGRect(x: btnLogin.bounds.width/2-90, y: btnLogin.bounds.height/2-18, width: 36, height: 36))
        if let img = self.wcMRaK5LBXrZ0wJz{
            btnLogin.addSubview(img)
            img.qianli_image(imgurl: "qianliLoading.gif")
        }
//        btnLogin.tag = 10 //说明在登录中
        btnLogin.isEnabled = false
        
        let deviceId = getDeviceID()
        let lgRequest = LoginRequest(device_id: deviceId, email_code: "", password: s_pw, user_name: s_mail)
        LoginViewModel.shared.PToBQUrjD0wWrDlk(loginRequest: lgRequest) { result in
            DispatchQueue.main.async { [weak self] in
                if let self = self{
                    switch result {
                    case .success(let loginResults):
                        if loginResults.code != 0 {
                            self.X7vYe1QunkSRgBBp(loginResults.msg)
                        }else if let _ = loginResults.data{
                            LoginViewModel.shared.isLogouted = false
                            self.X7vYe1QunkSRgBBp("")
                        }else{
                            self.X7vYe1QunkSRgBBp("\(LocalizedString("Login Failed"))：\(LocalizedString("Invalid Login Data"))")
                        }
                    case .failure(let error):
                        self.X7vYe1QunkSRgBBp("\(LocalizedString("Login Failed"))：\(error.localizedDescription)")
                    }
                }
            }
        }
        
    }
    
    func X7vYe1QunkSRgBBp(_ msg:String){
        if let lgimg = self.wcMRaK5LBXrZ0wJz{
            lgimg.removeFromSuperview()
        }
        if let btnLogin = self.rG0bPuFNG6wJFOou{
            btnLogin.isEnabled = true
            btnLogin.setTitle(LocalizedString("Login Now"), for: .normal)
        }
        
        if (msg.isEmpty){
            LoginViewModel.shared.isLogouted = false
            self.clFi25NuDNbscWXL()
            self.loginOKBlock?()
        }else{
            self.view.Qianli_Toast(msg)
        }
    }
    
    func ph2lqG56246k5nHN(){
        let registerVc = QianliUserRegisterVC()
        registerVc.modalPresentationStyle = .overFullScreen
        registerVc.registerOKBlock = {[weak self] mail,pw in
            if let self = self{
                if !mail.isEmpty,let inputmail = self.cWTPhgOUvVenvUrY{
                    inputmail.oC2j3DaaYowlc1xU(mail)
                }
                self.tROjzsCcyUM24nkk("")
            }
        }
        self.present(registerVc, animated: true)
    }
    
    private func ohye52Si8Tbit5fd(_ s_mail:String,_ s_pw:String){ //弃用 //已由服务端处理
        self.M62h1bVOydwY8i4y(LocalizedString("Register successful! Loading info, please wait...."))
        
        let deviceId = getDeviceID()
        let lgRequest = LoginRequest(device_id: deviceId, email_code: "", password: s_pw, user_name: s_mail)
        LoginViewModel.shared.PToBQUrjD0wWrDlk(loginRequest: lgRequest) { result in
            DispatchQueue.main.async { [weak self] in
                if let self = self{
                    switch result {
                    case .success(let loginResults):
                        if loginResults.code != 0 {
                            self.tROjzsCcyUM24nkk(loginResults.msg)
                        }else if let _ = loginResults.data{
                            LoginViewModel.shared.isLogouted = false
                            self.tROjzsCcyUM24nkk("")
                        }else{
                            self.tROjzsCcyUM24nkk("\(LocalizedString("Load Failed"))：\(LocalizedString("Invalid user data"))")
                        }
                    case .failure(let error):
                        self.tROjzsCcyUM24nkk("\(LocalizedString("Load Failed"))：\(error.localizedDescription)")
                        self.showLoginRetry("login.err:\(error.localizedDescription)")
                    }
                }
            }
        }
    }
    
    func tROjzsCcyUM24nkk(_ msg:String){
        self.l0JOXR3PG9RznwqZ()
        
        if (msg.isEmpty){
            LoginViewModel.shared.isLogouted = false
            self.clFi25NuDNbscWXL()
            self.autoLoginOKBlock?()
        }else{
            self.view.Qianli_Toast(msg)
        }
    }
    
    func I78xJTIx1AbmwUKi(){
        let loginVc = QianliResetUserpwVC()
        loginVc.modalPresentationStyle = .overFullScreen
        loginVc.resetOKBlock = {[weak self] mail in
            if let self = self{
                self.view.Qianli_Toast(LocalizedString("Reset Password Success，Please Login!"))
            }
        }
        self.present(loginVc, animated: true)
    }
}

extension QainliUserLoginVC:UITextViewDelegate{
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if URL.absoluteString == "action://userProtocol" {
            GX2Ex29xLYziOn3d()
            return false
        }else if URL.absoluteString == "action://userPrivate" {
            A5emqwsTzcFhVbln()
            return false
        }
        return true
    }
    
    private func GX2Ex29xLYziOn3d(){
        QianliVibrateEnum.selection.vibrate()
        if let url = URL(string: "https://help.qianli999.com/service-1.html"){
            let webpage = QainliProtocolWebPage(url: url,title: "服务协议")
            webpage.modalPresentationStyle = .overFullScreen
            self.present(webpage, animated: true)
        }
    }
    
    private func A5emqwsTzcFhVbln(){
        QianliVibrateEnum.selection.vibrate()
        if let url = URL(string: "https://help.qianli999.com/privacy-1.html"){
            let webpage = QainliProtocolWebPage(url: url,title: LocalizedString("PRIVACY POLICY"))
            webpage.modalPresentationStyle = .overFullScreen
            self.present(webpage, animated: true)
        }
    }
}
